let layer = layui.layer, $ = layui.$, form = layui.form;

/*初始化函数*/
layui.use(['layer', 'form'], function () {
    // 0.0 判断屏幕宽度，调整页面内容大小
    if (window.screen.width <= 768) {
        $("#main_content").css("padding", "2em 0").css("width", "100%");
    }
    // 0.1 获取个人信息：这个函数内加载了其他的函数
    load_myInfo();
})

/*加载个人信息的函数*/
function load_myInfo() {
    $.get("/user/myInfo", {"token": localStorage.getItem("token")}, function (result) {
        if (result.code === 200) {
            let myInfo = result.data;
            /*顶部*/
            $("#header_top span[name='username']").html(myInfo.username);
            /*头部菜单*/
            $("#header_menu img[name='head_portrait_url']").attr("src", myInfo.headPortraitUrl);
            $("#header_menu span[name='username']").html(myInfo.username);
            $("#header_menu span[name='blog_number']").html(myInfo.blogNumber);
            $("#header_menu span[name='comment_number']").html(myInfo.commentNumber);

            /*个人信息*/
            $("#myInfo strong[name='username']").html(myInfo.username);
            $("#myInfo span[name='UID']").html("( UID：" + myInfo.id + " )");
            $("#myInfo span[name='email']").html(myInfo.email);
            let str=myInfo.emailFlag==false?"未验证(邮箱验证对于忘记密码时的重置非常重要)":"已验证"
            $("#myInfo span[name='email_flag']").html(str);
            $("#myInfo span[name='phone']").html(myInfo.phone);
            $("#myInfo span[name='role_name']").html(myInfo.roleName);
            $("#myInfo span[name='head_portrait_url']").html(myInfo.headPortraitUrl);
            $("#myInfo span[name='address']").html(myInfo.address);
            $("#myInfo span[name='sex']").html(myInfo.sex);
            $("#myInfo span[name='blog_number']").html(myInfo.blogNumber);
            $("#myInfo span[name='comment_number']").html(myInfo.commentNumber);

            // 0.2加载博客列表
            blog_pageList(myInfo.id, 1, 5, true, false);

            // 0.3 加载评论信息列表
            comment_pageList(myInfo.id, 1, 5, true, false);

            // 0.4 对layer进行初始化
            $("input[name='phone']").val(result.data.phone);
            $("input[name='username']").val(result.data.username);
            $("input[name='role_name']").val(result.data.roleName);
            $("input[name='address']").val(result.data.address);
            check_sex(result.data.sex);
            $("input[name='email']").val(result.data.email);
            $("input[name='head_portrait_url']").val(result.data.headPortraitUrl);
            $("input[name='blog_number']").val(result.data.blogNumber);
            $("input[name='comment_number']").val(result.data.commentNumber);
            //check_username_head_portrait(result.data.username, result.data.headPortraitUrl);
        } else layer.msg(result.msg, {icon: 5});
    })
}

/*博客的分页函数*/
function blog_pageList(user_id, page_no, page_size, isRender, isTo) {
    $.get("/blog/info/page", {
        "user_id": user_id,
        "published": true,
        "flag": 0,
        "page_no": page_no,
        "page_size": page_size
    }, function (result) {
        if (result.code === 200) {
            let html_str = "";
            $.each(result.data, function (i, n) {
                html_str += '<div class="layui-card layui-bg-gray">';
                html_str += '<a href="/blog/blog_detail.html?id=' + n.id + '"><div class="layui-card-header"><h3><strong>' + n.title + '</strong></h3></div></a>';
                html_str += '<div class="layui-card-body"><div class="layui-row"><div class="layui-col-md3"><a href="/blog/blog_detail.html?id=' + n.id + '">';
                html_str += '<img src="' + n.imageUrl + '" alt="图片" style="height: auto;width: 100%"></a></div>';
                html_str += '<div class="layui-col-md8 layui-col-md-offset1"><div class="layui-row">' + n.description + '</div>';

                // 博客的标签信息
                html_str += '<div class="layui-row">';
                $.each(n.tagList, function (j, m) {
                    html_str += '<div class="layui-col-md2 layui-col-sm3 layui-col-xs6" style="padding: 0.5em 0.5em">';
                    html_str += '<button class="layui-btn layui-btn-primary layui-btn-radius layui-btn-xs" onclick="window.location.href=\'/blog/blog_tag.html?id=' + m.id + '\'" name="tag_id" value="' + m.id + '">';
                    html_str += m.name + '</button></div>';
                })
                html_str += '</div>';

                html_str += '<div class="layui-row layui-col-space4">';
                html_str += '<div class="layui-col-md1 layui-col-sm1"><img class="layui-nav-img" src="' + n.createUser.headPortraitUrl + '" alt=""></div>';
                html_str += '<div class="layui-col-md3 layui-col-sm3"><a href="#"><span class="layui-font-blue">' + n.createUser.username + '</span></a></div>';
                html_str += '<div class="layui-col-md3 layui-col-sm3"><i class="layui-icon layui-icon-date"></i>' + n.publishDate + '</div>';
                html_str += '<div class="layui-col-md2 layui-col-sm2"><i class="layui-icon layui-icon-senior"></i>' + n.viewTimes + '</div>';
                html_str += '<div class="layui-col-md3 layui-col-sm3"><button class="layui-btn layui-btn-xs layui-btn-radius">' + n.typeName + '</button></div>';
                html_str += '</div></div></div></div></div>';
            })
            $("#blog_list").html(html_str);
            if (isRender) {
                //执行一个laypage实例
                layui.laypage.render({
                    elem: 'blog_page_btn', //注意，这里的 test1 是 ID，不用加 # 号
                    count: result.total, //数据总数，从服务端得到
                    limit: 5,    //每页显示的条数。laypage将会借助 count 和 limit 计算出分页数。
                    theme: '#123456',//自定义主题
                    jump: function (obj, first) {//
                        // 当分页被切换时触发，函数返回两个参数：
                        // obj（当前分页的所有选项值）、first（是否首次，一般用于初始加载的判断）
                        //obj包含了当前分页的所有参数，比如：
                        //console.log(obj.curr); //得到当前页，以便向服务端请求对应页的数据。
                        //console.log(obj.limit); //得到每页显示的条数

                        //首次不执行
                        if (!first) {
                            //do something
                            blog_pageList(user_id, obj.curr, obj.limit, false, true);
                        }
                    }
                });
            }
            if (isTo)
                window.location.href = "#blog_list";
        } else layer.msg(result.msg);
    })
}

/*评论分页的函数*/
function comment_pageList(user_id, page_no, page_size, isRender, isTo) {
    $.get("/blog/comment/info", {
        //"blog_id": blog_id,
        "user_id": user_id,
        "page_no": page_no,
        "page_size": page_size
    }, function (result) {
        if (result.code === 200) {
            let html_str = "";
            $.each(result.data, function (i, n) {
                html_str += '<div class="layui-row layui-col-space4">';
                html_str += '<div class="layui-col-md2 layui-col-xs4">';
                html_str += '<img class="layui-nav-img" src="' + n.createUser.headPortraitUrl + '" alt="">';
                html_str += '<span class="layui-font-blue">' + n.createUser.username + '</span></div>';
                html_str += '<div class="layui-col-md2 layui-col-xs3"><i class="layui-icon layui-icon-date"></i>' + n.createTime + '</div></div>';
                html_str += '<div class="layui-row" style="padding: 0 2em 1em 2em">';
                html_str += '<p>' + n.content + '</p></div>';
            })
            $("#comment_list").html(html_str);
            if (isRender) {
                //执行一个laypage实例
                layui.laypage.render({
                    elem: 'comment_page', //注意，这里的 test1 是 ID，不用加 # 号
                    count: result.total, //数据总数，从服务端得到
                    limit: 5,    //每页显示的条数。laypage将会借助 count 和 limit 计算出分页数。
                    theme: '#123456',//自定义主题
                    jump: function (obj, first) {//
                        // 当分页被切换时触发，函数返回两个参数：
                        // obj（当前分页的所有选项值）、first（是否首次，一般用于初始加载的判断）
                        //obj包含了当前分页的所有参数，比如：
                        //console.log(obj.curr); //得到当前页，以便向服务端请求对应页的数据。
                        //console.log(obj.limit); //得到每页显示的条数

                        //首次不执行
                        if (!first) {
                            //do something
                            comment_pageList(user_id, obj.curr, obj.limit, false, true);
                        }
                    }
                });
            }
            if (isTo)
                window.location.href = "#comment_list";
        } else layer.msg(result.msg, {icon: 5});
    })
}

// 修改个人信息的函数
function edit_myInfo() {
    $("#submitBtnDiv").prop("hidden", false);
    $("input[name='phone']").prop("disabled", true);
    let $username = $("input[name='username']").prop("disabled", false);
    $("input[name='role_name']").prop("disabled", true);
    let $address = $("input[name='address']").prop("disabled", false);
    $("input[name='sex']").prop("disabled", false);
    $("input[name='email']").prop("disabled", true);
    let $head_portrait_url = $("input[name='head_portrait_url']").prop("disabled", false);
    $("input[name='blog_number']").prop("disabled", true);
    $("input[name='comment_number']").prop("disabled", true);

    let username = $username.val();
    let address = $address.val();
    let sex = $("input[name='sex']:checked").val();
    let head_portrait_url = $head_portrait_url.val();

    let edit_layer_index = layer.open({
        type: 1,
        title: '个人信息',
        content: $("#userInfoLayer"),
        closeBtn: 2,
        area: ["300px", "auto"],
        anim: 3,
        cancel: function (index, layero) {
            // 值复原
            $username.val(username);
            $address.val(address);
            check_sex(sex);
            $head_portrait_url.val(head_portrait_url);
            layer.close(index);
        }
    })
    // 2.1 更新按钮
    form.on('submit(formSubmit)', function (data) {
        //console.log(data.elem) //被执行事件的元素DOM对象，一般为button对象
        //console.log(data.form) //被执行提交的form对象，一般在存在form标签时才会返回
        //console.log(data.field) //当前容器的全部表单字段，名值对形式：{name: value}
        let update_load_index = layer.load(1);
        $.ajax({
            url: "/user/myInfo",
            method: "put",
            dataType: "json",
            data: {
                "token": localStorage.getItem("token"),
                "username": $.trim(data.field.username),
                "head_portrait_url": $.trim(data.field.head_portrait_url),
                "address": $.trim(data.field.address),
                "sex": $.trim(data.field.sex),
            },
            success: function (result) {
                if (result.code === 200) {
                    layer.close(edit_layer_index);
                    // 刷新头像和用户名
                    check_username_head_portrait(data.field.username, data.field.head_portrait_url);
                    // 刷新个人信息
                    $("#myInfo span[name='head_portrait_url']").html(data.field.head_portrait_url);
                    $("#myInfo span[name='sex']").html(data.field.sex);
                    $("#myInfo span[name='address']").html(data.field.address);
                    // 刷新session中的个人信息
                    sessionStorage.setItem("myInfo_username",data.field.username);
                    sessionStorage.setItem("myInfo_headPortraitUrl",data.field.head_portrait_url);
                } else
                    layer.msg(result.msg, {icon: 5});
                layer.close(update_load_index);
            }
        })
        return false; //阻止表单跳转。如果需要表单跳转，去掉这段即可。
    });
    // 2.2 取消按钮
    $("#cancelBtn").click(function () {
        layer.close(edit_layer_index);
        // 值复原
        $username.val(username);
        $address.val(address);
        check_sex(sex);
        $head_portrait_url.val(head_portrait_url);
        return false; //阻止表单跳转。如果需要表单跳转，去掉这段即可。
    })
}

/*选择性别的函数*/
function check_sex(sex) {
    $("input[name='sex']").prop("checked", false);
    $("input[name='sex'][value='" + sex + "']").prop("checked", true);
    layui.form.render("radio");//刷新单选框
}

/*检查头像和用户名的函数*/
function check_username_head_portrait(username, headPortraitUrl) {
    let $username = $("span[name='username']");
    if ($username.html() !== username) {
        $username.html(username);
        $("strong[name='username']").html(username);
    }
    let $url = $("img[name='head_portrait_url']");
    if ($url.attr("src") !== headPortraitUrl) {
        $url.attr("src", headPortraitUrl);
    }
}

/*修改密码的函数*/
function reset_pwd() {
    let reset_pwd_layer_index = layer.open({
        type: 1,
        title: '修改密码',
        content: $("#reset_pwd_layer"),
        closeBtn: 2,
        //area: ["300px", "400px"],
        anim: 3,
        success: function (layero, index) {
            $("#reset_pwd_btn").click();
        },
        cancel: function (index, layero) {
            // 值复原
            $("#reset_pwd_btn").click();
            layer.close(index);
        }
    })
    // 2.1 更新按钮
    form.on('submit(form_reset_pwd)', function (data) {
        let password = data.field.password;
        let password_confirm = data.field.password_confirm;
        if (password !== password_confirm) {
            layer.msg("两次密码不一致", {icon: 5});
            return false;
        }
        //console.log(data.elem) //被执行事件的元素DOM对象，一般为button对象
        //console.log(data.form) //被执行提交的form对象，一般在存在form标签时才会返回
        //console.log(data.field) //当前容器的全部表单字段，名值对形式：{name: value}
        let load_index = layer.load(1);
        $.ajax({
            url: "/user/resetPwd",
            method: "put",
            data: {
                "token": localStorage.getItem("token"),
                "password": password
            },
            success: function (result) {
                layer.close(load_index);
                if (result.code === 200) {
                    layer.close(reset_pwd_layer_index);
                    layer.confirm('密码修改成功；是否重新登录?', {icon: 3, title: '提示'}, function (index) {
                        localStorage.removeItem("token");
                        layer.close(index);
                        window.location.href = "/index.html";
                    });
                } else
                    layer.msg(result.msg, {icon: 5});
            }
        })
        return false; //阻止表单跳转。如果需要表单跳转，去掉这段即可。
    });
}

/*自定义背景图的函数*/
function reset_bg() {
    let reset_bg_layer_index = layer.open({
        type: 1,
        title: '自定义背景图',
        content: $("#reset_bg_layer"),
        closeBtn: 2,
        //area: ["300px", "400px"],
        anim: 3,
        success: function (layero, index) {
            $("#reset_bg_btn").click();
            $.get("/blog/img_url", function (result) {
                if (result.code === 200) {
                    let html_str = "";
                    $.each(result.data, function (i, n) {
                        if (i < 9) {
                            html_str += '<a onclick="check_bg(\'' + n.value + '\');">';
                            html_str += '<img src="' + n.value + '" alt="图片未找到" border="0" style="width: 160px;height: 160px"></a>';
                            if (i === 2 || i === 5)
                                html_str += "<br/>";
                        }
                    })
                    $("#reset_bg_layer div[name='bg_div']").html(html_str);
                } else layer.msg(result.msg, {icon: 5});
            })
        },
        cancel: function (index, layero) {
            // 值复原
            $("#reset_bg_btn").click();
            layer.close(index);
        }
    })
    // 2.1 更新按钮
    form.on('submit(form_bg_pwd)', function (data) {
        let background_image_url = $.trim(data.field.background_image_url);
        let opacity = $.trim(data.field.opacity);
        if (background_image_url === "") {
            layer.msg("url不能为空", {icon: 5});
            return false;
        }
        localStorage.setItem("background_image_url", background_image_url);
        localStorage.setItem("opacity", opacity);
        layer.close(reset_bg_layer_index);
        window.location.reload();
        return false; //阻止表单跳转。如果需要表单跳转，去掉这段即可。
    });
}

/*选中背景图的函数*/
function check_bg(url) {
    $("#reset_bg_layer input[name='background_image_url']").val(url);
}